//
//  CustomButton.swift
//  yuejian
//
//  Created by gyy on 2017/11/3.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit

class CustomButton: UIButton {

    private var shape:CAShapeLayer!
    private let duration:Double = 1.5
    private var _titleColor:UIColor!
    private var index = 0
    
    var circleColor = UIColor.white
    var count:Double = 10
    
    private var titleColor:UIColor{
        set{
            if index == 0{
                _titleColor = newValue
                index += 1
            }
        }
        get{
            return _titleColor
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }
    
    private  func initialize(){
        let replicatorLayer = CAReplicatorLayer()
        replicatorLayer.frame = bounds
        replicatorLayer.instanceCount = Int(count)
        replicatorLayer.instanceTransform = CATransform3DMakeRotation(.pi/180*CGFloat(360/count), 0, 0, 1)
        replicatorLayer.instanceDelay = duration/count
        layer.addSublayer(replicatorLayer)
        
        shape = CAShapeLayer()
        shape.frame = CGRect(x: 0, y: 0, width: bounds.height*0.015, height: bounds.height*0.015)
        shape.position = CGPoint(x: bounds.width/2, y: shape.bounds.width*10/2+0.1*bounds.height)
        shape.backgroundColor = circleColor.cgColor
        shape.cornerRadius = shape.bounds.width/2
        shape.isHidden = true
        replicatorLayer.addSublayer(shape)
    }
    
    func animation(){
        shape.isHidden = false
        titleColor = currentTitleColor
        setTitleColor(.clear, for: .normal)
        
        let anim = CABasicAnimation(keyPath: "transform.scale")
        anim.fromValue = 10
        anim.toValue = 1
        anim.duration = duration
        anim.repeatCount = HUGE
        shape.add(anim, forKey: nil)
    }
    
    func stopAnimation(){
        shape.isHidden = true
        setTitleColor(titleColor, for: .normal)
        shape.removeAllAnimations()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

